<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body>
		<h1>hello</h1>
		<h1>删掉所有添加的文件</h1>
		<script>
			let DB_NAME = 'user';
			let DB_VERSION = 1.01;
			let db;
			(function initDb() {
				let DB = indexedDB.open(DB_NAME, DB_VERSION);
				DB.onsuccess = event => {
					db = event.target.result;
					console.log('数据库打开成功!');
				};
				DB.onerror = err => {
					console.log(err);
				};

				DB.onupgradeneeded = event => {
					console.log('表创建成功');
					db = event.target.result;
					let objectStore;
					if (!db.objectStoreNames.contains('person')) {
						objectStore = db.createObjectStore('person', { keyPath: 'id' });
					}
				};
			})();

			function insertData(tables, table, data) {
				let req = db.transaction(tables, 'readwrite').objectStore(table).add(data);
				return new Promise((resolve, reject) => {
					req.onsuccess = res => {
						resolve(res.target); //readyState: "done" ,result: 3  error:null
					};
					req.onerror = err => {
						reject(err.target.error);
					};
				});
			}

			function updateData() {
				db.transaction(['person'], 'readwrite').objectStore('person').put({
					id: 1,
					name: '郭兆',
					age: 28,
					height: 180,
				});
			}

			function deleteItem() {
				db.transaction(['person'], 'readwrite').objectStore('person').delete(1); // key
			}

			function getdata(tables, table, key) {
				return new Promise((resolve, reject) => {
					const req = db.transaction(tables, 'readwrite').objectStore(table).get(key);
					req.onsuccess = res => {
						resolve(res.target.result);
					};
					req.onerror = err => {
						reject(err.target.error);
					};
				});
			}

			setTimeout(() => {
				getdata(['person'], 'person', 2).then(res => {
					console.log(res);
				});
			}, 200);
		</script>
	</body>
</html>
